import { 
  _decorator, assetManager,color,Component, director, EventTouch, Graphics, ImageAsset,
  input, Input, Node, Sprite, SpriteFrame, Texture2D, UITransform, Vec2, Vec3,
} from 'cc';
const { ccclass, property } = _decorator;
const wx = window['wx'];
@ccclass('abatt')
export class abatt extends Component {
    @property(Node) avatar: Node = null;        // 节点

    @property(Node)
    drawNode : Node = null;

    @property(Node)
    testnode : Node = null;

    @property
    public r = 0;

    x = 0;
    y = 0;
    k = null;
    numDots = 12;
    maxDis = 600;
    thouched: boolean = false;
    Speed: Vec3[] = [];
    dotcolor: Vec3[] = [];
    position: any[];
    startPos: Vec2;
    movePos: Vec2;


    protected onLoad(): void {
      const winsize = screen;
      this.drawNode.on(Input.EventType.TOUCH_START,this.onStart,this);
      this.drawNode.on(Input.EventType.TOUCH_START,this.onMove,this);
      this.drawNode.on(Input.EventType.TOUCH_END,this.onEnd,this);

      this.position = [];
      this.maxDis = winsize.width * 1.5;
      for(let i = 0; i < this.numDots; i++){
          this.position.push([0,0]);
          this.x = this.getRandom(0 ,winsize.width - this.r * 4);
          this.y = this.getRandom(0,winsize.height - this.r * 4);
          this.position[i] = new Vec2(this.x,this.y);
          const speed = new Vec3(this.getRandom(-20, 20), this.getRandom(-20, 20), this.getRandom(0, 0));
          this.Speed.push(speed);
          const dotcolor = new Vec3(this.getRandom(0,255),this.getRandom(0,255),this.getRandom(0,255));
          this.dotcolor.push(dotcolor);
          console.log('position',i,this.position[i]);
      }

    }

    onStart(event: EventTouch){
      // let pos = event.touch.getUILocation();
      // for(let i = 0; i < this.numDots; i++){
      //   if(this.isPointInDot(pos,this.position[i])){
      //     this.k = i;
      //     this.thouched= true;
      //     // this.position[i] = pos;
      //     console.log('开始时坐标',i,this.position[i]);
      //   }
      // }

    }

    onMove(event: EventTouch){
      let pos = event.touch.getUILocation();

      for (let i = 0; i < this.numDots; i++) {
        if (this.isPointInDot(pos, this.position[i])) {
          this.k = i;
          this.thouched = true;
          // this.position[i] = pos;
          console.log('圆内坐标', i, this.position[i]);
        }
      }
      // if (this.thouched) {
      //   this.position[this.k].x = pos.x;
      //   this.position[this.k].y = pos.y;
      //   console.log('移动时坐标',this.k,this.position[this.k],pos);
      // }

    }

    onEnd(event: EventTouch){
      let pos = event.touch.getUILocation();
      if(!(this.k === null)){
        this.position[this.k].x = pos.x;
        this.position[this.k].y = pos.y;
      }
      this.k = null;
      this.thouched = false;
    }

    isPointInDot(p1: Vec2, p2: { x: number; y: number; }){
      const d = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
      return d <= this.r;

    }

    getRandom( min: number, max: number){
      return Math.floor(Math.random() * (max + 1 - min) + min);
    }
    start() {
      this.draw();
    }
    protected onDestroy(): void {
      input.off(Input.EventType.TOUCH_START,this.onStart,this);
      input.off(Input.EventType.TOUCH_START,this.onMove,this);
      input.off(Input.EventType.TOUCH_END,this.onEnd,this);
      
    }
    draw(){
      const g = this.drawNode.getComponent(Graphics);
      const length = this.position.length - 1;
      for(let i = 0; i < this.position.length; i++){
          const p = this.position[i];
          this.drawPos(p.x,p.y,this.r,this.dotcolor[i]);
          if(i > 0){
            const p1 = this.position[i-1];
            const p2 = this.position[i];
            const d = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
            if(d > this.maxDis){
              continue;
            }
            const alpha = 1 - d/this.maxDis;
            g.moveTo(p1.x,p1.y);
            g.lineTo(p2.x,p2.y);
            g.strokeColor = color( 0, 0, 0, 255 * alpha);
            g.stroke();
          }
          if(i == length) {
            g.moveTo(this.position[0].x,this.position[0].y);
            g.lineTo(this.position[length].x,this.position[length].y);
            g.close();
            g.stroke();
          }
          // for (let j = i + 1; j < this.position.length; j++) { 
          //     const p2 = this.position[j];
          //     const d = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
          //     if(d > this.maxDis){
          //         continue;
          //     }
          //     const alpha = 1 - d/this.maxDis;
          //     g.moveTo(p1.x,p1.y);
          //     g.lineTo(p2.x,p2.y);
          //     g.strokeColor = color( 0, 0, 0, 255 * alpha);
          //     g.stroke();
          // }
      }
  }
  drawPos(x: number, y: number, r: number, i: Vec3){
    const g = this.drawNode.getComponent(Graphics);
    g.lineWidth = 5;
    g.fillColor = color( i.x, i.y, i.z, 255);
    g.arc(x,y,r,0,2 * Math.PI,false);
    g.fill();
}

    update(dt: number) {
      const winsize = screen;
      const g = this.drawNode.getComponent(Graphics);
      for(let i = 0; i < this.position.length; i++){
        this.position[i].x += this.Speed[i].x * dt;
        this.position[i].y += this.Speed[i].y * dt;
        this.dotcolor[i].x += this.Speed[i].z * dt;
        this.dotcolor[i].y += this.Speed[i].z * dt;
        this.dotcolor[i].z += this.Speed[i].z * dt;

        if(this.position[i].x <= 0 || this.position[i].x >= winsize.width){
            this.Speed[i].x = -this.Speed[i].x;
        }
        if(this.position[i].y <= 0 || this.position[i].y >= winsize.height){
            this.Speed[i].y = -this.Speed[i].y;
        }

        if(this.dotcolor[i].x <= 0 || this.dotcolor[i].x >= 255){
            this.Speed[i].z = -this.Speed[i].z;
        }
        if(this.dotcolor[i].y <= 0 || this.dotcolor[i].y >= 255){
            this.Speed[i].z = -this.Speed[i].z;
        }
        if(this.dotcolor[i].z <= 0 || this.dotcolor[i].z >= 255){
            this.Speed[i].z = -this.Speed[i].z;
        }

        this.position[i].x = Math.max(0, Math.min(this.position[i].x,winsize.width));
        this.position[i].y = Math.max(0, Math.min(this.position[i].y,winsize.height));
      }
      g.clear();
      this.draw();
        
    }

    goback(){
        director.loadScene('Home')
    }
    getUserInfo(){
      const that = this;
      wx.getSetting({
        success (res){
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function(res) {
                var userInfo = res.userInfo
                var nickName = userInfo.nickName
                var avatarUrl = userInfo.avatarUrl
                console.log(res.userInfo)
                that.setAvatar(avatarUrl);
              }
            })
          } else {
            let button = wx.createUserInfoButton({
              type: 'text',
              text: '获取用户信息',
              style: {
                left: 10,
                top: 76,
                width: 200,
                height: 40,
                lineHeight: 40,
                backgroundColor: '#ff0000',
                color: '#ffffff',
                textAlign: 'center',
                fontSize: 16,
                borderRadius: 4
              }
            })
            button.onTap((res) => {
              if(res.userInfo){
                var userInfo = res.userInfo
                var nickName = userInfo.nickName
                var avatarUrl = userInfo.avatarUrl
                console.log(res)
                that.setAvatar(avatarUrl);
                button.destroy();
              }else{
                console.log('拒绝授权')
              }
            })
          }
        }
      })

    }

    setAvatar(avatarUrl) {
      const url = avatarUrl;
      let spire = this.avatar.getComponent(Sprite);
      console.log('获取URL',avatarUrl)
      assetManager.loadRemote<ImageAsset>(url, { ext: '.jpg' }, function (err, imageAsset) {
        console.log('url',url);
        console.log('load remote');
        if (err) {
          return console.error(err.message);
        }
        let spriteFrame = new SpriteFrame();
        let texture = new Texture2D();
        texture.image = imageAsset;
        spriteFrame.texture = texture;
        spire.spriteFrame = spriteFrame;
      })


    }



}


